package dicky.fortunetelling.logic;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;

import android.content.ContentValues;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.provider.Settings;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.json.JSONArray;
import org.json.JSONObject;

import android.util.Log;


/**
* @author Dicky
*
*/
public class DatabaseUtil {
	private static String TAG = DatabaseUtil.class.getSimpleName();
	private static String DB_PATH = "";
	private static String DB_NAME = "db.db";
	private static final String TABLE_NAME = "word";
	private static SQLiteDatabase db;
	private static Cursor mCursor;
	private static char base64EncodeChars[] = {
	    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 
	    'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 
	    'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 
	    'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 
	    'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 
	    'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', 
	    '8', '9', '+', '/'
	};
	private static byte base64DecodeChars[] = {
	    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
	    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
	    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
	    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
	    -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 
	    54, 55, 56, 57, 58, 59, 60, 61, -1, -1, 
	    -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 
	    5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 
	    15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 
	    25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 
	    29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 
	    39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 
	    49, 50, 51, -1, -1, -1, -1, -1
	};
	
	/* (non-Javadoc)
	* @see com.phonegap.api.Plugin#execute(java.lang.String, org.json.JSONArray, java.lang.String)
	*/
	
	public static String encode(String s)
	{
	    StringBuffer sb = new StringBuffer();
	    byte[] data=s.getBytes();
	    int len = data.length;
	    int i = 0;
	    do
	    {
	        if(i >= len)
	            break;
	        int b1 = data[i++] & 0xff;
	        if(i == len)
	        {
	            sb.append(base64EncodeChars[b1 >>> 2]);
	            sb.append(base64EncodeChars[(b1 & 3) << 4]);
	            sb.append("==");
	            break;
	        }
	        int b2 = data[i++] & 0xff;
	        if(i == len)
	        {
	            sb.append(base64EncodeChars[b1 >>> 2]);
	            sb.append(base64EncodeChars[(b1 & 3) << 4 | (b2 & 0xf0) >>> 4]);
	            sb.append(base64EncodeChars[(b2 & 0xf) << 2]);
	            sb.append("=");
	            break;
	        }
	        int b3 = data[i++] & 0xff;
	        sb.append(base64EncodeChars[b1 >>> 2]);
	        sb.append(base64EncodeChars[(b1 & 3) << 4 | (b2 & 0xf0) >>> 4]);
	        sb.append(base64EncodeChars[(b2 & 0xf) << 2 | (b3 & 0xc0) >>> 6]);
	        sb.append(base64EncodeChars[b3 & 0x3f]);
	    } while(true);
	    return sb.toString();
	}

	public static String decode(String str)
	{
	    byte data[] = str.getBytes();
	    int len = data.length;
	    ByteArrayOutputStream buf = new ByteArrayOutputStream(len);
	    int i = 0;
	    do
	    {
	        if(i >= len)
	            break;
	        int b1;
	        do
	            b1 = base64DecodeChars[data[i++]];
	        while(i < len && b1 == -1);
	        if(b1 == -1)
	            break;
	        int b2;
	        do
	            b2 = base64DecodeChars[data[i++]];
	        while(i < len && b2 == -1);
	        if(b2 == -1)
	            break;
	        buf.write(b1 << 2 | (b2 & 0x30) >>> 4);
	        int b3;
	        do
	        {
	            b3 = data[i++];
	            if(b3 == 61)
	                return new String(buf.toByteArray());
	            b3 = base64DecodeChars[b3];
	        } while(i < len && b3 == -1);
	        if(b3 == -1)
	            break;
	        buf.write((b2 & 0xf) << 4 | (b3 & 0x3c) >>> 2);
	        int b4;
	        do
	        {
	            b4 = data[i++];
	            if(b4 == 61)
	                return new String(buf.toByteArray());
	            b4 = base64DecodeChars[b4];
	        } while(i < len && b4 == -1);
	        if(b4 == -1)
	            break;
	        buf.write((b3 & 3) << 6 | b4);
	    } while(true);
	    return new String(buf.toByteArray());
	}
	
	public static SQLiteDatabase openDataBase(Context context) throws Exception {
		DB_PATH = context.getApplicationInfo().dataDir+"/databases/";
		Log.d(TAG, DB_PATH);
		File jhPath = new File(DB_PATH+DB_NAME);
		// 查看数据库文件是否存在
		if (jhPath.exists()) {
			// 存在则直接返回打开的数据库
			return SQLiteDatabase.openOrCreateDatabase(jhPath, null);
		} else {
			// 不存在先创建文件夹
			File path = new File(DB_PATH);
			if (path.mkdir()) {
				Log.d(TAG,"创建成功");
			} else {
				Log.d(TAG,"创建失败");
			}
			// 得到资源
			AssetManager am = context.getAssets();
			// 得到数据库的输入流
			InputStream is = am.open(DB_NAME);
			// 用输出流写到SDcard上面
			FileOutputStream fos = new FileOutputStream(jhPath);
			// 创建byte数组 用于1KB写一次
			byte[] buffer = new byte[1024];
			int count = 0;
			while ((count = is.read(buffer)) > 0) {
				fos.write(buffer, 0, count);
			}
			// 最后关闭就可以了
			fos.flush();
			fos.close();
			is.close();
			// 如果没有这个数据库 我们已经把他写到SD卡上了，然后在执行一次这个方法 就可以返回数据库了
			return openDataBase(context);
		}
	}

	/**
	 * 
	 * @param ctx
	 * @param uuid 设备ID
	 * @param userid 数据库用户ID，系统数据为SYS
	 * @param args	保存内容，以JSONArray传入
	 * 				args[0]代表whereClause（查询条件），whereClause为空值代表查询所有记录，否则根据whereClause值代为SQL查询语句的一部分；
	 * 				args[1]代表tcode（业务代码），tcode为空值代表查询所有业务记录，否则根据tcode值代为SQL查询语句tcode的一部分；
	 * 				args[2]代表listcount（最多显示记录数），listcount为空值代表查询所有记录，否则根据listcount值代为SQL查询语句limit的一部分；
	 * 				args[3]代表sflag（即时查询标记），用于判断查询服务服务器内容还是本地数据库,1：即时查询服务器、0：查询本地数据库；
	 * @param callbackId	plugin生成的ID，主要用于长连接，可以传空值
	 * @return
	 * @throws Exception
	 */
	public static JSONObject toSearchRecord(Context ctx,String keys,String orderkey) throws Exception {
		JSONObject obj = new JSONObject();
		JSONArray lists = new JSONArray();
		JSONObject item = new JSONObject();
		try{
			Log.d(TAG, "toSearchRecord start");
			
			db=openDataBase(ctx);
			String whereClause=" where 1=1 ";
			
			if (!"".equals(keys)){
				whereClause += " and "+keys;
			}
	        
			int count=0;
	        String ordersql="";
	        if (!"".equals(orderkey)){
	        	ordersql=" order by "+orderkey;
	        }
	        String sql="select * from "+TABLE_NAME +whereClause+ordersql;
	        Log.d(TAG, "toSearchRecord sql:"+sql);
//			mCursor = db.query(TABLE_NAME,null,whereClause,null,null,null,null);
	        mCursor = db.rawQuery(sql, null);
			int c=mCursor.getCount();
			if (c==0){
				obj.put("status", "1");
				obj.put("mes", "找不到相关数据！");
				obj.put("rows", lists);
				obj.put("count", count);
			}
			else{
				String id="";
				String word="";
				String kxword="";
				String kxnum="";
				String five="";
	
				mCursor.moveToFirst();
				do {
					id=getColumnValue(mCursor,"id");
					word=getColumnValue(mCursor,"word");
					kxword=getColumnValue(mCursor,"kxword");
					kxnum=getColumnValue(mCursor,"kxnum");
					five=getColumnValue(mCursor,"five");

					item.put("id", id);
					item.put("word", word);
					item.put("kxword", kxword);
					item.put("kxnum", kxnum);
					item.put("five", five);
					lists.put(item);
					item = new JSONObject(); 
				} while (mCursor.moveToNext());
			}
			count=lists.length();
			obj.put("status", "1");
			obj.put("rows", lists);
			obj.put("count", count);
			Log.d(TAG, "toSearchRecord Success count:" + count);
		} catch (Exception e) {
			Log.d(TAG, "toSearchRecord Exception " + e);
			throw e;
		}finally {
			if (mCursor!=null){
				mCursor.close();
			}
			if (db!=null){
				db.close();
			}
		}
		Log.d(TAG, "toSearchRecord end");
		return obj;
	}

	private static String getColumnValue(Cursor cursor,String ColumnName){
		String value=cursor.getString(cursor.getColumnIndex(ColumnName))==null?"":cursor.getString(cursor.getColumnIndex(ColumnName));
		return value;
	}

}